import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  EyeOutlined,
  FilterOutlined,
  HeartOutlined,
  MoreOutlined,
  PlusOutlined,
  SaveOutlined,
  SearchOutlined,
  SendOutlined,
  ShareAltOutlined,
  StarOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import {
  ProCard,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
} from "@ant-design/pro-components";
import {
  Alert,
  AutoComplete,
  Avatar,
  Badge,
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Descriptions,
  Divider,
  Drawer,
  Dropdown,
  Empty,
  Form,
  Input,
  InputNumber,
  List,
  Mentions,
  Menu,
  Modal,
  Popconfirm,
  Progress,
  Radio,
  Rate,
  Result,
  Row,
  Select,
  Slider,
  Space,
  Spin,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Tooltip,
  Transfer,
  Typography,
  Upload,
  message,
} from "antd";
import type { MenuProps } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import dayjs from "dayjs";

import React, { useEffect, useState } from "react";

const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;

interface FileItem {
  uid: string;
  name: string;
  status: "done" | "uploading" | "error";
  url?: string;
  size: number;
  type: string;
}

interface FormData {
  name: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  salary: number;
  startDate: string;
  description: string;
}

const Page28: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");
  const [modalVisible, setModalVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [formData, setFormData] = useState<FormData | null>(null);
  const [tableData, setTableData] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState("");
  const [rating, setRating] = useState(4);
  const [sliderValue, setSliderValue] = useState(50);
  const [switchValue, setSwitchValue] = useState(true);
  const [checkboxValues, setCheckboxValues] = useState<string[]>([]);
  const [radioValue, setRadioValue] = useState("option1");
  const [transferValue, setTransferValue] = useState<string[]>([]);
  const [mentionsValue, setMentionsValue] = useState("");
  const [autoCompleteValue, setAutoCompleteValue] = useState("");

  useEffect(() => {
    // 模拟表格数据
    const mockTableData = [
      {
        key: "1",
        name: "张三",
        age: 32,
        address: "北京市朝阳区",
        department: "技术部",
        position: "前端工程师",
        salary: 15000,
        status: "active",
        joinDate: "2023-01-15",
        performance: 85,
      },
      {
        key: "2",
        name: "李四",
        age: 28,
        address: "上海市浦东新区",
        department: "设计部",
        position: "UI设计师",
        salary: 12000,
        status: "active",
        joinDate: "2023-03-20",
        performance: 92,
      },
      {
        key: "3",
        name: "王五",
        age: 35,
        address: "广州市天河区",
        department: "产品部",
        position: "产品经理",
        salary: 18000,
        status: "inactive",
        joinDate: "2022-11-10",
        performance: 78,
      },
    ];
    setTableData(mockTableData);
  }, []);

  // 文件上传相关事件
  const handleFileUpload = (info: any) => {
    const { file, fileList } = info;
    setFileList(fileList);

    if (file.status === "done") {
      message.success(`${file.name} 上传成功`);
    } else if (file.status === "error") {
      message.error(`${file.name} 上传失败`);
    }
  };

  const handleFilePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewVisible(true);
    setPreviewTitle(
      file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1),
    );
  };

  const handleFileRemove = (file: UploadFile) => {
    message.success(`删除文件: ${file.name}`);
  };

  const getBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  // 表单相关事件
  const handleFormSubmit = async (values: any) => {
    setLoading(true);
    try {
      console.log("表单数据:", values);
      message.success("表单提交成功！");
      setFormData(values);
      setModalVisible(true);
    } catch (error) {
      message.error("表单提交失败！");
    } finally {
      setLoading(false);
    }
  };

  const handleFormReset = () => {
    form.resetFields();
    message.info("表单已重置");
  };

  const handleFormValidate = async () => {
    try {
      const values = await form.validateFields();
      message.success("表单验证通过！");
      console.log("验证通过的数据:", values);
    } catch (error) {
      message.error("表单验证失败！");
    }
  };

  // 表格相关事件
  const handleTableRowClick = (record: any) => {
    message.info(`点击了行: ${record.name}`);
  };

  const handleTableSelectionChange = (selectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(selectedRowKeys);
    message.info(`选中了 ${selectedRowKeys.length} 行`);
  };

  const handleTableSearch = (value: string) => {
    setSearchText(value);
    message.info(`搜索: ${value}`);
  };

  // 其他交互事件
  const handleRatingChange = (value: number) => {
    setRating(value);
    message.success(`评分: ${value} 星`);
  };

  const handleSliderChange = (value: number) => {
    setSliderValue(value);
    message.info(`滑块值: ${value}`);
  };

  const handleSwitchChange = (checked: boolean) => {
    setSwitchValue(checked);
    message.success(`开关状态: ${checked ? "开启" : "关闭"}`);
  };

  const handleCheckboxChange = (checkedValues: string[]) => {
    setCheckboxValues(checkedValues);
    message.info(`复选框: ${checkedValues.join(", ")}`);
  };

  const handleRadioChange = (e: any) => {
    setRadioValue(e.target.value);
    message.info(`单选框: ${e.target.value}`);
  };

  const handleTransferChange = (targetKeys: string[]) => {
    setTransferValue(targetKeys);
    message.info(`穿梭框: ${targetKeys.length} 项`);
  };

  const handleMentionsChange = (value: string) => {
    setMentionsValue(value);
  };

  const handleAutoCompleteChange = (value: string) => {
    setAutoCompleteValue(value);
  };

  // 操作按钮事件
  const handleAddClick = () => {
    message.success("点击了新增按钮");
  };

  const handleEditClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请先选择要编辑的项目");
      return;
    }
    message.info(`编辑项目: ${selectedRowKeys.join(", ")}`);
    setDrawerVisible(true);
  };

  const handleDeleteClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请先选择要删除的项目");
      return;
    }
    message.success(`删除项目: ${selectedRowKeys.join(", ")}`);
    setSelectedRowKeys([]);
  };

  const handleExportClick = () => {
    message.loading("正在导出数据...", 2).then(() => {
      message.success("数据导出成功！");
    });
  };

  const handleImportClick = () => {
    message.info("点击了导入按钮");
  };

  const handleSaveClick = () => {
    message.success("数据保存成功！");
  };

  const handleSendClick = () => {
    message.success("数据发送成功！");
  };

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (text) => (
        <a onClick={() => message.info(`查看 ${text} 详情`)}>{text}</a>
      ),
    },
    {
      title: "年龄",
      dataIndex: "age",
      key: "age",
      sorter: true,
    },
    {
      title: "部门",
      dataIndex: "department",
      key: "department",
      filters: [
        { text: "技术部", value: "技术部" },
        { text: "设计部", value: "设计部" },
        { text: "产品部", value: "产品部" },
      ],
    },
    {
      title: "职位",
      dataIndex: "position",
      key: "position",
    },
    {
      title: "薪资",
      dataIndex: "salary",
      key: "salary",
      sorter: true,
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => (
        <Tag color={status === "active" ? "green" : "red"}>
          {status === "active" ? "在职" : "离职"}
        </Tag>
      ),
    },
    {
      title: "绩效",
      dataIndex: "performance",
      key: "performance",
      render: (value) => <Progress percent={value} size="small" />,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => message.info(`编辑 ${record.name}`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗？"
            onConfirm={() => message.success(`删除 ${record.name}`)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 穿梭框数据
  const transferData = [
    { key: "1", title: "选项1", description: "描述1" },
    { key: "2", title: "选项2", description: "描述2" },
    { key: "3", title: "选项3", description: "描述3" },
    { key: "4", title: "选项4", description: "描述4" },
    { key: "5", title: "选项5", description: "描述5" },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>页面 28 - 复杂表单与文件管理</Title>

      <Tabs defaultActiveKey="1">
        <TabPane tab="表单操作" key="1">
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <ProCard title="基础表单">
                <ProForm
                  form={form}
                  onFinish={handleFormSubmit}
                  submitter={{
                    searchConfig: {
                      submitText: "提交",
                      resetText: "重置",
                    },
                    render: (props, doms) => {
                      return (
                        <Space>
                          {doms}
                          <Button onClick={handleFormValidate}>验证</Button>
                          <Button
                            onClick={handleSaveClick}
                            icon={<SaveOutlined />}
                          >
                            保存
                          </Button>
                          <Button
                            onClick={handleSendClick}
                            icon={<SendOutlined />}
                          >
                            发送
                          </Button>
                        </Space>
                      );
                    },
                  }}
                >
                  <ProFormText
                    name="name"
                    label="姓名"
                    placeholder="请输入姓名"
                    rules={[{ required: true, message: "请输入姓名" }]}
                  />
                  <ProFormText
                    name="email"
                    label="邮箱"
                    placeholder="请输入邮箱"
                    rules={[
                      { required: true, message: "请输入邮箱" },
                      { type: "email", message: "请输入正确的邮箱格式" },
                    ]}
                  />
                  <ProFormText
                    name="phone"
                    label="电话"
                    placeholder="请输入电话"
                    rules={[{ required: true, message: "请输入电话" }]}
                  />
                  <ProFormSelect
                    name="department"
                    label="部门"
                    options={[
                      { label: "技术部", value: "tech" },
                      { label: "设计部", value: "design" },
                      { label: "产品部", value: "product" },
                      { label: "运营部", value: "operation" },
                    ]}
                    placeholder="请选择部门"
                    rules={[{ required: true, message: "请选择部门" }]}
                  />
                  <ProFormUploadButton
                    name="avatar"
                    label="头像上传"
                    max={1}
                    fieldProps={{
                      name: "file",
                      listType: "picture-card",
                      beforeUpload: () => false,
                    }}
                  />
                </ProForm>
              </ProCard>
            </Col>

            <Col span={12}>
              <ProCard title="高级表单组件">
                <Space direction="vertical" style={{ width: "100%" }}>
                  <div>
                    <Text>评分: </Text>
                    <Rate value={rating} onChange={handleRatingChange} />
                  </div>
                  <div>
                    <Text>进度: {sliderValue}%</Text>
                    <Slider value={sliderValue} onChange={handleSliderChange} />
                  </div>
                  <div>
                    <Text>开关: </Text>
                    <Switch
                      checked={switchValue}
                      onChange={handleSwitchChange}
                    />
                  </div>
                  <div>
                    <Text>复选框: </Text>
                    <Checkbox.Group
                      options={[
                        { label: "选项A", value: "a" },
                        { label: "选项B", value: "b" },
                        { label: "选项C", value: "c" },
                      ]}
                      value={checkboxValues}
                      onChange={handleCheckboxChange}
                    />
                  </div>
                  <div>
                    <Text>单选框: </Text>
                    <Radio.Group
                      value={radioValue}
                      onChange={handleRadioChange}
                    >
                      <Radio value="option1">选项1</Radio>
                      <Radio value="option2">选项2</Radio>
                      <Radio value="option3">选项3</Radio>
                    </Radio.Group>
                  </div>
                  <div>
                    <Text>提及: </Text>
                    <Mentions
                      value={mentionsValue}
                      onChange={handleMentionsChange}
                      placeholder="输入 @ 提及用户"
                      style={{ width: 200 }}
                    />
                  </div>
                  <div>
                    <Text>自动完成: </Text>
                    <AutoComplete
                      value={autoCompleteValue}
                      onChange={handleAutoCompleteChange}
                      placeholder="输入搜索内容"
                      style={{ width: 200 }}
                      options={[
                        { value: "选项1", label: "选项1" },
                        { value: "选项2", label: "选项2" },
                        { value: "选项3", label: "选项3" },
                      ]}
                    />
                  </div>
                </Space>
              </ProCard>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="文件管理" key="2">
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <ProCard title="文件上传">
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onChange={handleFileUpload}
                  onPreview={handleFilePreview}
                  onRemove={handleFileRemove}
                  beforeUpload={() => false}
                >
                  {fileList.length >= 8 ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传</div>
                    </div>
                  )}
                </Upload>
              </ProCard>
            </Col>

            <Col span={12}>
              <ProCard title="文件列表">
                <List
                  dataSource={fileList}
                  renderItem={(file) => (
                    <List.Item
                      actions={[
                        <Button
                          key="preview"
                          type="link"
                          onClick={() => handleFilePreview(file)}
                        >
                          预览
                        </Button>,
                        <Button
                          key="download"
                          type="link"
                          onClick={() => message.info(`下载 ${file.name}`)}
                        >
                          下载
                        </Button>,
                        <Popconfirm
                          key="delete"
                          title="确定删除吗？"
                          onConfirm={() => handleFileRemove(file)}
                        >
                          <Button type="link" danger>
                            删除
                          </Button>
                        </Popconfirm>,
                      ]}
                    >
                      <List.Item.Meta
                        avatar={<Avatar icon={<EyeOutlined />} />}
                        title={file.name}
                        description={`${(file.size! / 1024).toFixed(2)} KB`}
                      />
                    </List.Item>
                  )}
                />
              </ProCard>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="数据表格" key="3">
          <ProCard>
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddClick}
              >
                新增
              </Button>
              <Button icon={<EditOutlined />} onClick={handleEditClick}>
                编辑
              </Button>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleDeleteClick}
              >
                删除
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExportClick}>
                导出
              </Button>
              <Button icon={<UploadOutlined />} onClick={handleImportClick}>
                导入
              </Button>
              <Input.Search
                placeholder="搜索..."
                onSearch={handleTableSearch}
                style={{ width: 200 }}
              />
            </Space>

            <Table
              columns={columns}
              dataSource={tableData}
              rowSelection={{
                selectedRowKeys,
                onChange: handleTableSelectionChange,
              }}
              onRow={(record) => ({
                onClick: () => handleTableRowClick(record),
              })}
              pagination={{
                total: tableData.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              }}
            />
          </ProCard>
        </TabPane>

        <TabPane tab="穿梭框" key="4">
          <ProCard title="数据穿梭">
            <Transfer
              dataSource={transferData}
              titles={["源数据", "目标数据"]}
              targetKeys={transferValue}
              onChange={handleTransferChange}
              render={(item) => item.title}
              showSearch
              showSelectAll={false}
            />
          </ProCard>
        </TabPane>
      </Tabs>

      {/* 图片预览模态框 */}
      <Modal
        open={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="example" style={{ width: "100%" }} src={previewImage} />
      </Modal>

      {/* 表单数据预览模态框 */}
      <Modal
        title="表单数据预览"
        open={modalVisible}
        onOk={() => setModalVisible(false)}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        {formData && (
          <Descriptions column={1}>
            <Descriptions.Item label="姓名">{formData.name}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{formData.email}</Descriptions.Item>
            <Descriptions.Item label="电话">{formData.phone}</Descriptions.Item>
            <Descriptions.Item label="部门">
              {formData.department}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 编辑抽屉 */}
      <Drawer
        title="编辑数据"
        placement="right"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={400}
      >
        <p>这里是编辑表单的内容</p>
      </Drawer>
    </div>
  );
};

export default Page28;
